﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Business.EntityFrameworkCore;
using mozhi.smarterp.Business.Enums;
using mozhi.smarterp.Business.Purchases;
using mozhi.smarterp.Business.Purchases.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.Business.Repositories.Purchase
{
    public class PurchaseOrderRepository : DocumentEfCoreRepository<BusinessDbContext, PurchaseOrder, Guid>, IPurchaseOrderRepository
    {
        public PurchaseOrderRepository(IDbContextProvider<BusinessDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<long> GetCountAsync(string number, DateTime? startDate, DateTime? endDate, DocumentStatusType status, PurchaseOrderType? type, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<PurchaseOrder>().AsNoTracking()
                .WhereIf(!number.IsNullOrEmpty(), x => x.Number.Contains(number))
                .WhereIf(startDate.HasValue, x => x.Date >= startDate)
                .WhereIf(endDate.HasValue, x => x.Date <= endDate)
                .WhereIf(status != default, x => x.Status == status)
                .WhereIf(type.HasValue, x => x.Type == type)
                .CountAsync(cancellationToken);
            return count;
        }

        public async Task<List<PurchaseOrder>> GetPagedListAsync(string number, DateTime? startDate, DateTime? endDate, DocumentStatusType status, PurchaseOrderType? type, int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var orders = await dbContext.Set<PurchaseOrder>().AsNoTracking()
                .WhereIf(!number.IsNullOrEmpty(), x => x.Number.Contains(number))
                .WhereIf(startDate.HasValue, x => x.Date >= startDate)
                .WhereIf(endDate.HasValue, x => x.Date <= endDate)
                .WhereIf(status != default, x => x.Status == status)
                .WhereIf(type.HasValue, x => x.Type == type)
                .OrderByIf<PurchaseOrder, IQueryable<PurchaseOrder>>(!sorting.IsNullOrWhiteSpace(), sorting)
                .PageBy(skipCount, maxResultCount)
                .ToListAsync(cancellationToken);
            return orders;
        }
    }
}
